package com.zdy.showgoods;

import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.example.networklibrary.BaseObserver;
import com.example.networklibrary.MD5;
import com.example.networklibrary.RxHttp;
import com.example.networklibrary.SharedPreferencesUtils;
import com.example.networklibrary.ToastUtils;
import com.example.networklibrary.config.KeyInterface;
import com.example.networklibrary.entity.RequestEntity;
import com.example.networklibrary.model.QuestionsModel;
import com.example.networklibrary.model.RFID;
import com.example.networklibrary.model.UserInfo;
import com.zdy.modellibrary.base.BaseActivity;
import com.zdy.service.RFIDReadService;
import com.zdy.utils.CheckUtil;
import com.zdy.widget.MultiCheckDialogFragment;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

public class ActivityLogin extends BaseActivity implements View.OnClickListener {
    EditText loginCodeEdit;
    TextView toLoginBtn;
    private String staffCode = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        loginCodeEdit = findViewById(R.id.login_code);
        toLoginBtn = findViewById(R.id.login_btn);
        toLoginBtn.setOnClickListener(this);
        initService();
        EventBus.getDefault().register(this);
    }

    @Override
    protected void onResume() {
        staffCode = "";
        SharedPreferencesUtils.setString(ActivityLogin.this, KeyInterface.StaffInfo, "");
        super.onResume();
        loginCodeEdit.setVisibility(View.INVISIBLE);
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }


    @Subscribe
    public void receiveTag(RFID rfid) {
        if (TextUtils.isEmpty(SharedPreferencesUtils.getString(ActivityLogin.this, KeyInterface.StaffInfo))) {
            if (!staffCode.equals(rfid.getCode()))
                toLogin(rfid.getCode());
        }
    }

    private void toLogin(String code) {
        if (!CheckUtil.checkLoginCode(code)) {
            Toast.makeText(this, "请刷卡或者输入员工号登陆", Toast.LENGTH_SHORT).show();
            loginCodeEdit.setVisibility(View.VISIBLE);
            return;
        }
        staffCode = code;
        RequestEntity requestEntity = new RequestEntity();
        JSONObject id = new JSONObject();
        id.put("staff_number", code);
        requestEntity.setBody(id);
        JSONObject header = new JSONObject();
        header.put("request_seq", KeyInterface.REQUEST_SEQ);

        header.put("sign", "");
        header.put("sys_id", KeyInterface.SYS_ID);
        header.put("tra_code", KeyInterface.STAFF_LOGIN);
        requestEntity.setHeader(header);

        try {
            String signString = JSONObject.toJSONString(requestEntity);
            String sign = MD5.getSign(signString);
            header.put("sign", sign);
            requestEntity.setHeader(header);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String json = "";
        try {
            json = URLEncoder.encode(JSONObject.toJSONString(requestEntity), "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        RxHttp.getInstance()
                .getSyncServer()
                .login(SharedPreferencesUtils.getString(this, KeyInterface.AppURL), json)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<UserInfo>() {
                    @Override
                    public void onSuccess(UserInfo result) {
                        try {
                            SharedPreferencesUtils.setString(ActivityLogin.this, KeyInterface.StaffInfo, JSONObject.toJSONString(result));
                            toMain();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(Throwable e, String errorMsg) {
                        ToastUtils.showShort("登录失败");
                        loginCodeEdit.setVisibility(View.VISIBLE);
                    }
                });
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.login_btn) {
            toLogin(loginCodeEdit.getText().toString());
        }
    }

    private void toMain() {
        Intent intent = new Intent(this, ActivityMain.class);
        startActivity(intent);
    }

    /**
     * Service
     */
    private void initService() {
        // 开启绑定服务
        // 总结一下调用bindService之后发生的事情:
        // client 执行 bindService ->
        // 如果Service不存在，Service 执行 onCreate ->
        // 如果没有执行过onBind，Service 执行 onBind ->
        // client的实例ServiceConnection 执行 onServiceConnected
        Intent intent = new Intent(this, RFIDReadService.class);
        bindService(intent, mRFIDReadServiceConnection, BIND_AUTO_CREATE);
    }


    private RFIDReadService mRFIDReadService;
    private boolean mRFIDReadServiceIsBound;

    private ServiceConnection mRFIDReadServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            mRFIDReadServiceIsBound = true;
            RFIDReadService.MyBinder mBinder = (RFIDReadService.MyBinder) iBinder;
            mRFIDReadService = mBinder.getService();
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            mRFIDReadServiceIsBound = false;
        }
    };
}
